package com.hqd.ch03.v36.beans.support;

import com.hqd.ch03.v36.beans.TypeConverter;
import com.hqd.ch03.v36.beans.TypeConverterDelegate;
import com.hqd.ch03.v36.beans.property.support.PropertyEditorRegistrySupport;
import com.hqd.ch03.v36.core.MethodParameter;
import com.hqd.ch03.v36.core.convert.TypeDescriptor;
import com.sun.corba.se.impl.io.TypeMismatchException;

import java.lang.reflect.Field;

public class TypeConverterSupport extends PropertyEditorRegistrySupport implements TypeConverter {
    protected TypeConverterDelegate typeConverterDelegate;


    @Override

    public <T> T convertIfNecessary(Object value, Class<T> requiredType) throws TypeMismatchException {
        return convertIfNecessary(value, requiredType, TypeDescriptor.valueOf(requiredType));
    }

    public <T> T convertIfNecessary(Object value, Class<T> requiredType,
                                    MethodParameter methodParam) throws TypeMismatchException {

        return convertIfNecessary(value, requiredType,
                (methodParam != null ? new TypeDescriptor(methodParam) : TypeDescriptor.valueOf(requiredType)));
    }

    public <T> T convertIfNecessary(Object value, Class<T> requiredType, Field field)
            throws TypeMismatchException {

        return convertIfNecessary(value, requiredType,
                (field != null ? new TypeDescriptor(field) : TypeDescriptor.valueOf(requiredType)));
    }


    public <T> T convertIfNecessary(Object value, Class<T> requiredType,
                                    TypeDescriptor typeDescriptor) throws TypeMismatchException {
        try {
            return this.typeConverterDelegate.convertIfNecessary(null, null, value, requiredType, typeDescriptor);
        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage());
        }
    }
}
